package com.rowline.admin.module.util.interceptor;

import com.alibaba.fastjson.JSON;
import com.rowline.admin.module.util.constant.ContextContants;
import com.rowline.admin.module.util.context.RequestContext;
import com.rowline.admin.module.util.context.SessionContext;
import com.rowline.admin.module.util.domain.User;
import com.rowline.admin.module.util.domain.Log;
import com.rowline.admin.module.util.domain.ResponseMessage;
import com.rowline.admin.module.util.utils.HttpRequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.rowline.admin.module.util.utils.HttpRequestUtil.isAjax;

/**
 * ClassName:AuthWebInterceptor
 * Created by 245167
 * on 2017/8/11  11:46
 * description:登录权限拦截器
 */
@Component
public class AuthWebInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception {
        Log.info("sprinMVC AuthWebInterceptor preHandle(。。。)");
        String requestURI = request.getRequestURI();
        if(StringUtils.isNotBlank(request.getQueryString())){
            requestURI += "?"+request.getQueryString();
        }
        String paramStr = JSON.toJSONString(HttpRequestUtil.getParamers(request));
        Log.info("请求资源："+requestURI + " @" +paramStr);
        if(!isAjax(request))
            SessionContext.setSession(ContextContants.LAST_URL_SESSION_KEY, requestURI);
        User user = SessionContext.getCurrentUser();
        Object userMessage =  SessionContext.getSession("userMessage");

        ResponseMessage re = new ResponseMessage();
        if (userMessage == null) {
            // 如果是json请求
            re.setIsSuccess(false);
            re.setResponseCode(ContextContants.ERROR_CODE_NOLOGIN);
            re.setMessage("登录超时，请重新登录后再执行操作");
            re.setNextUrl(request.getContextPath() + "/login/toLogin.do");
            outPutResponse(response, isAjax(request), re);
            return false;
        } else {	//判断是否有公司信息
            Object companyMessage =  SessionContext.getSession("companyMessage");
            System.out.println("companyMessage is " + companyMessage);
            if(companyMessage==null){
                re.setIsSuccess(false);
                re.setResponseCode(ContextContants.ERROR_CODE_NOLOGIN);
                re.setMessage("使用系统前，请先填写您完整的用户信息");
                re.setNextUrl(request.getContextPath() + "/register/toRegister.do");
                outPutResponse(response, isAjax(request), re);
                return false;
            }
        }
        RequestContext.currentContext();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object o,
                           ModelAndView modelAndView) throws Exception {
        Log.info("sprinMVC AuthWebInterceptor postHandle(。。。)");
        RequestContext.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object o, Exception e) throws Exception {
        Log.info("sprinMVC AuthWebInterceptor afterCompletion(。。。)");
    }

    /**
     * 输出
     */
    private void outPutResponse(HttpServletResponse response,
                                Boolean isAjax,
                                ResponseMessage rMsg) throws Exception {

        if (isAjax) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(rMsg));
        } else {
            response.sendRedirect(rMsg.getNextUrl());
        }

    }
}
